package com.df.ez_game.server.gateway;

import com.df.ez_game.server.UserLifeCycleCb;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;

public class UserManager {
    private final static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //注意 与 NonBlockingHashMapLong的区别
    private final static ConcurrentHashMap<Long,UserSession> userId2Session = new ConcurrentHashMap<>();
    private final static ConcurrentHashMap<String,UserSession> channelId2Session = new ConcurrentHashMap<>();

    public final static Set<UserLifeCycleCb> handlers = new HashSet<>();


    public static UserSession getSessionByChannelId(String channelId){
        return channelId2Session.get(channelId);
    }


    public static boolean login(String channnelId,Long userId){
        UserSession userSession = channelId2Session.get(channnelId);
        if (Objects.isNull(userSession)) {
            return false;
        }

        if (Boolean.FALSE.equals(userSession.isActive())) {
            removeUserSession(userSession);
            return false;
        }

        userSession.setUserId(userId);

        userId2Session.put(userId, userSession);

        //发出事件
//        // 上线通知
//        if (userSession.isVerifyIdentity()) {
//            this.userHookInto(userSession);
//        }

        return true;
    }
    public static void removeUserSession(UserSession userSession) {

        if (Objects.isNull(userSession)) {
            return;
        }

        if (userSession.getState() == 0) {
            return;
        }

//        String userChannelId = userSession.getChannelHashId();
//        long userId = userSession.getUserId();
//
//        Channel channel = userSession.getChannel();
//        userId2Session.remove(userId);
//        channelId2Session.remove(userChannelId);
//        group.remove(channel);

//        if (userSession.getState() == UserSessionState.ACTIVE && userSession.isVerifyIdentity()) {
//            userSession.setState(UserSessionState.DEAD);
//            this.userHookQuit(userSession);
//        }
        //TODO 发布事件

        // 关闭用户的连接
//        channel.close();
    }


    public static void lifeCycle(Consumer<UserLifeCycleCb> function){
        for (UserLifeCycleCb handler : handlers) {
            try {
                function.accept(handler);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static int getLoginedCount() {

        return userId2Session.size();
    }

    public static int getConnectCount() {
        return channelId2Session.size();
    }
}
